<?php
namespace app\plus\controller;

use app\common\model\ShopOrderModel;
use app\common\model\ShopPaymentModel;
use app\common\model\ShopPromotionAuctionLogModel;
use app\common\model\ShopCardOrderModel;
use app\common\model\ShopPromotionGroupbuyCartModel;
use Payment\ChargeContext;
use Payment\Config;
use Payment\NotifyContext;
use think\Controller;
use think\helper\Str;

class WxpayController extends Controller
{

    //获取微信配置参数
    private function getWxConfig($siteId)
    {
        $paymentModel            = new ShopPaymentModel();
        $payInfo                 = $paymentModel->where('site_id', $siteId)->where('pay_code', 'wxpay')->find();
        $wxconfig                = $payInfo->pay_config;
        $wxconfig['time_expire'] = 30;
        $notifyConfig            = $this->setNotify($siteId);
        $wxconfig                = array_merge($wxconfig, $notifyConfig);
        return $wxconfig;
    }

    public function pay()
    {
        $siteId                 = $this->request->param('site_id');
        $orderType              = $this->request->param('order_type');
        $orderSn                = $this->request->param('order_sn');
        $device                 = $this->request->param('device'); //1、手机端 2电脑端 3微信端
        $wxconfig               = $this->getWxConfig($siteId);
        $payData                = $this->getOrder($orderType, $orderSn);
        $payData['client_ip']   = get_client_ip();
        if ($device == 3) { //微信内支付
            $type   = Config::WX_CHANNEL_PUB; // 微信 公众号支付
            $openid = $this->request->param('openid');
            if ($openid == '') {
                $this->error('微信参数获取失败！');
            }
            $payData['openid'] = $openid;// 需要通过微信提供的api获取该openid
        } else { //扫码支付
            $type = Config::WX_CHANNEL_QR;    // 微信 扫码支付
            // 微信扫码支付，需要设置的参数
            $payData['product_id'] = $orderSn;
        }
        if (empty($payData)) {
            $this->error('参数错误！');
        }
        $charge = new ChargeContext();
        try {
            $charge->initCharge($type, $wxconfig);
            $ret = $charge->charge($payData);
            if ($device != 3) { //扫码支付
                $ret = str_encode($ret);
            }
            $this->success('初始化成功！', '', $ret);
        } catch (PayException $e) {
            $this->error($e->errorMessage());
        }
    }

    /**
     * 获取订单信息
     * @param $orderType
     * @param $orderId
     * PS:必须提供 order_no、amount、subject、body、client_ip
     */
    private function getOrder($orderType, $orderSn)
    {
        $payData = [];
        switch ($orderType) {
            case 'groupbuy_cart': //保证金详情
                $groupbuyCartModel = new ShopPromotionGroupbuyCartModel();
                $order             = $groupbuyCartModel->where('order_sn', $orderSn)->find();
                $payData           = ['order_no' => $order['order_sn'], 'amount' => $order['margin'], 'subject' => $order['order_sn'] . '缴纳保证金', 'body' => $order['goods_name'], 'extra_param'=>'groupbuy_cart'];
                break;

            case 'order': //订单详情
                $orderModel = new ShopOrderModel();
                $order      = $orderModel->where('order_sn', $orderSn)->find();
                $payData           = ['order_no' => $order['order_sn'], 'amount' => $order['order_price'], 'subject' => $order['order_sn'] . '订单支付', 'body' => $order['order_sn'] . '订单支付', 'extra_param'=>'order'];
                break;

            case 'auction': //保证金详情
                $auctionModel = new ShopPromotionAuctionLogModel();
                $order             = $auctionModel->where('pay_sn', $orderSn)->find();
                $payData           = ['order_no' => $order['pay_sn'], 'amount' => $order['money'], 'subject' => $order['pay_sn'] . '缴纳竞拍保障金', 'body' => $order['goods_name'], 'extra_param'=>'auction'];
                break;

            case 'card': //优惠券支付
                $auctionModel = new ShopCardOrderModel();
                $order             = $auctionModel->where('order_sn', $orderSn)->find();
                $payData           = [
                    'order_no' => $order['order_sn'],
                    'amount' => $order['order_price'],
                    'subject' => $order['order_sn'] . '购买优惠券',
                    'body' => $order['card_name'],
                    'extra_param'=>'card',
                    'time_expire'=>$order['end_time']
                ];
                break;

        }
        return $payData;
    }

    /**
     * 设置回调地址
     * @param $orderType
     */
    private function setNotify($siteId)
    {
        $config['notify_url'] = $this->request->domain() . '/plus/wxpay/notify/site_id/'.$siteId.'.html';
        $config['return_url'] = '';
        return $config;
    }

    /**
     * 回调地址
     */
    public function notify()
    {
        $siteId = $this->request->param('site_id');
        $notify    = new NotifyContext();
        $callback  = new \app\plus\notify\PayNotify();
        $wxconfig = $this->getWxConfig($siteId);
        // 支付宝回调
        $notify->initNotify(Config::WEIXIN, $wxconfig);
        $notify->notify($callback);
    }

    /**
     * 获取支付用户openid
     */
    public function getOpenid()
    {
        $siteId       = $this->request->param('site_id/d', 0);
        $url       = urldecode($this->request->param('url'));
        $paymentModel = new ShopPaymentModel();
        $payInfo      = $paymentModel->where('site_id', $siteId)->where('pay_code', 'wxpay')->find();
        $wxconfig     = $payInfo->pay_config;
        $options = ['appid' => $wxconfig['app_id'], 'appsecret' => $wxconfig['appsecret']];
        $oauth   = &load_wechat('Oauth', $options);
        // 执行接口操作
        $result = $oauth->getOauthRedirect(get_current_url(), 'pay', 'snsapi_base');
        if(!isset($_GET['code'])){
            $this->redirect($result);
        }
        $result = $oauth->getOauthAccessToken();
        // 接口异常的处理
        if ($result === FALSE) {
            exit($oauth->errCode);
        } else {
            $this->redirect($url.'&openid='.$result['openid']);
        }
    }

}